﻿using Microsoft.EntityFrameworkCore;
using SmartCity.BasicData.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SmartCity.BasicData.Repo
{
    // created by FuMingJun
    public class BaseReposity<T> : IBaseRepository<T> where T :BaseEntity
    {
        private readonly SCDbcontext db;

        public BaseReposity(SCDbcontext db)
        {
            this.db = db;
        }
        public Task<int> CreateAsync(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expression)
        {
            return await db.Set<T>().Where(expression).ToListAsync();
        }

        public async Task<T> GetModelAsync(long id)
        {
            return await db.Set<T>().FindAsync(id);   
        }
        /// <summary>
        /// 返回查询表达式
        /// </summary>
        /// <returns></returns>
        public Task<IQueryable<T>> QueryAllAsync()
        {
            return Task.FromResult(db.Set<T>().AsQueryable<T>()) ; //select * from T  where xxx 
        }

        public Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChangesAsync();
        }
    }
}
